﻿using IOT4Week1Day1.Domain.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOT4Week1Day1.EFCore.Repositories
{
    public class EfRepository<T> : IRepository<T> where T : class  //where T这个是对T类型进行泛型约束
    {
        //定义一个上下文的私有只读 字段
        private readonly MyDbContext _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public EfRepository(MyDbContext db)  //完成依赖注入
        {
            _db = db;
        }

        /// <summary>
        /// 添加T类型的数据
        /// </summary>
        /// <param name="model"></param>
        public void Add(T model)
        {
            _db.Set<T>().Add(model); // Set<T>()这个方法是获取T的集合
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void Delete(object id)
        {
            T model = _db.Set<T>().Find(id);  //先查

            _db.Set<T>().Remove(model);  //后删
        }

        /// <summary>
        /// 批删
        /// </summary>
        /// <param name="ids"></param>
        public void DeleteAll(string[] ids)
        {
            foreach (var id in ids)
            {
                Delete(id);   //循环 单删
            }
        }

        /// <summary>
        /// 根据主键查一条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T Get(object id)
        {
            T model = _db.Set<T>().Find(id);  //先查
            return model;
        }

        /// <summary>
        /// 获取整个表的查询对象IQueryable<T>
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetTable()
        {
            return _db.Set<T>().AsQueryable();  //不是返回集合List，而是返回IQueryable接口（select * from XXX表）
        }

        /// <summary>
        /// 保存修改
        /// </summary>
        /// <returns></returns>
        public int Save()
        {
            try
            {
                return _db.SaveChanges(); //保存修改的时候，才会执行增 删、改的SQL语句，以及事务处理
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存修改的时候发生了异常：{0}", ex.Message);
                throw;
            }
            
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        public void Update(T model)
        {
            _db.Set<T>().Update(model);
        }
    }
}
